<?php
	header("Content-type: application/x-javascript");
?>

Ext.define('AmpleHarvest.GUI.component.filter.cSelector',
{   extend : 'Ext.button.Button',
    alias : 'widget.metricsviewer-view-grids-filterselector',

    ignoreCols : [],
    cols : [],
    text : 'Filter',
    tooltip : 'Select columns to filter',

    menu		:
			{
        items : []
    },

    listeners : {
        render : function (button) {
            this.reconfigure.call(this, this.getGrid());
            this.getGrid().mon(this.getGrid(), 'reconfigure', this.reconfigure, this);
        }
    },

    getGrid : function () {
        if (!this.grid) {
            this.grid = this.up('gridpanel');
        }
        return this.grid;
    },

    reconfigure : function (grid) {
        var items, i, colCount, col, name;

        this.menu.removeAll(true); // start with a clean slate
        this.cols = [];

        items = [ {
            xtype : 'menucheckitem',
            text : 'All Columns',
            checked : true,
            hideOnClick : false,
            scope : this,
            checkHandler : function (item, checked) {
                this.menu.items.each(function (item) {
                    if (item.isXType('menucheckitem')) {
                        item.setChecked(checked);
                    }
                });
            }
        }, '-' ];

        colCount = grid.columns.length;
        for (i = 0; i < colCount; i++) {
            col = grid.columns[i];
            if (col.dataIndex && (!this.ignoreCols || Ext.Array.indexOf(this.ignoreCols, col.dataIndex) === -1)) {
                name = col.text || col.dataIndex;
                if (name && Ext.Array.indexOf(this.cols, name) === -1) {
                    this.cols[this.cols.length] = name;

                    items[items.length] = {
                        xtype : 'menucheckitem',
                        text : name,
                        checked : true,
                        hideOnClick : false,
                        dataIndex : col.dataIndex
                    };
                }
            }
        }

        this.menu.add(items);

        grid.getStore().on('beforeload', function () {
            var filterItems = [];

            store = this.getGrid().getStore();
            this.menu.items.each(function (item) {
                if (item.isXType('menucheckitem') && item.checked && item.dataIndex) {
                    filterItems[filterItems.length] = item.dataIndex;
                }
            });

            Ext.apply(store.proxy.extraParams, {
                filterItems : filterItems
            });
        }, this);
    }

});